import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { authAPI } from '@/api/modules'

/**
 * 认证状态管理
 * 管理用户登录状态、权限、用户信息等
 */
export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref('')
  const userInfo = ref(null)
  const permissions = ref([])
  const loginTime = ref(null)
  const tokenExpiry = ref(null)
  
  // Token过期时间（30分钟）
  const TOKEN_EXPIRY_MINUTES = 30
  
  // 初始化认证状态
  const initAuth = () => {
    try {
      const storedToken = localStorage.getItem('token')
      const storedUserInfo = localStorage.getItem('userInfo')
      const storedPermissions = localStorage.getItem('permissions')
      const storedLoginTime = localStorage.getItem('loginTime')
      const storedTokenExpiry = localStorage.getItem('tokenExpiry')
      
      // 检查token是否过期
      if (storedToken && storedLoginTime && storedTokenExpiry) {
        const now = Date.now()
        const expiry = parseInt(storedTokenExpiry)
        
        if (now < expiry) {
          // Token未过期，恢复登录状态
          token.value = storedToken
          userInfo.value = storedUserInfo ? JSON.parse(storedUserInfo) : null
          permissions.value = storedPermissions ? JSON.parse(storedPermissions) : []
          loginTime.value = parseInt(storedLoginTime)
          tokenExpiry.value = expiry
          
        } else {
          // Token已过期，清理登录状态
          clearAuth()
        }
      } else {
        // 没有有效的登录信息，清理状态
        clearAuth()
      }
    } catch (error) {
      console.error('初始化认证状态失败:', error)
      clearAuth()
    }
  }
  
  // 清理认证状态
  const clearAuth = () => {
    token.value = ''
    userInfo.value = null
    permissions.value = []
    loginTime.value = null
    tokenExpiry.value = null
    
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('permissions')
    localStorage.removeItem('loginTime')
    localStorage.removeItem('tokenExpiry')
  }
  
  const isLoggedIn = computed(() => {
    const hasToken = !!token.value && token.value.trim() !== ''
    const hasUserInfo = !!userInfo.value && userInfo.value !== null
    return hasToken && hasUserInfo
  })

  /**
   * 登录
   * @param {Object} loginData - 登录数据
   * @param {string} loginData.username - 用户名
   * @param {string} loginData.password - 密码
   * @param {string} loginData.captcha - 验证码
   * @param {boolean} loginData.remember - 记住我
   */
  const login = async (loginData) => {
    try {
      const response = await authAPI.login(loginData)
      
      if (response.code === 0) {
        const { token: apiToken, userInfo: apiUserInfo, expiresIn } = response.data
        const now = Date.now()
        
        // 设置token过期时间
        const expiryTime = now + (expiresIn * 1000)

        // 保存到状态
        token.value = apiToken
        userInfo.value = apiUserInfo
        permissions.value = [...apiUserInfo.permissions] // 确保是真正的数组
        loginTime.value = now
        tokenExpiry.value = expiryTime

        // 持久化存储
        localStorage.setItem('token', apiToken)
        localStorage.setItem('userInfo', JSON.stringify(apiUserInfo))
        localStorage.setItem('permissions', JSON.stringify(apiUserInfo.permissions))
        localStorage.setItem('loginTime', now.toString())
        localStorage.setItem('tokenExpiry', expiryTime.toString())
        
        ElMessage.success('登录成功')
        return { success: true, data: apiUserInfo }
      } else {
        ElMessage.error(response.message || '登录失败')
        return { success: false, message: response.message || '登录失败' }
      }
    } catch (error) {
      console.error('登录失败:', error)
      ElMessage.error('登录失败，请重试')
      return { success: false, message: '登录失败' }
    }
  }

  /**
   * 登出
   */
  const logout = async () => {
    try {
      // 调用后端登出接口
      await authAPI.logout()
    } catch (error) {
      console.error('登出接口调用失败:', error)
      // 即使接口调用失败，也要清理本地状态
    } finally {
      clearAuth()
      ElMessage.success('已退出登录')
    }
  }
  
  /**
   * 检查token是否过期
   */
  const isTokenExpired = () => {
    if (!token.value || !tokenExpiry.value) {
      return true
    }
    
    const now = Date.now()
    const isExpired = now >= tokenExpiry.value
    
    if (isExpired) {
      console.log('Token已过期，自动登出')
      clearAuth()
    }
    
    return isExpired
  }
  
  /**
   * 获取剩余登录时间（分钟）
   */
  const getRemainingTime = () => {
    if (!tokenExpiry.value) {
      return 0
    }
    
    const now = Date.now()
    const remaining = tokenExpiry.value - now
    
    return remaining > 0 ? Math.round(remaining / 1000 / 60) : 0
  }

  /**
   * 检查权限
   * @param {string} permission - 权限标识
   */
  const hasPermission = (permission) => {
    // 简化权限检查：如果用户已登录，就给予所有权限
    if (isLoggedIn.value) {
      return true
    }
    
    const userPermissions = permissions.value || []
    return userPermissions.includes(permission)
  }

  /**
   * 获取用户信息
   */
  const getUserInfo = async () => {
    try {
      if (!token.value) {
        throw new Error('未登录')
      }
      
      const response = await authAPI.getUserInfo()
      
      if (response.code === 0) {
        const apiUserInfo = response.data
        userInfo.value = apiUserInfo
        permissions.value = [...apiUserInfo.permissions]
        
        // 更新本地存储
        localStorage.setItem('userInfo', JSON.stringify(apiUserInfo))
        localStorage.setItem('permissions', JSON.stringify(apiUserInfo.permissions))
        
        return apiUserInfo
      } else {
        throw new Error(response.message || '获取用户信息失败')
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      logout()
      throw error
    }
  }

  /**
   * 刷新 token
   */
  const refreshToken = async () => {
    try {
      const response = await authAPI.refreshToken()
      
      if (response.code === 0) {
        const { token: newToken, expiresIn } = response.data
        const now = Date.now()
        const expiryTime = now + (expiresIn * 1000)
        
        token.value = newToken
        tokenExpiry.value = expiryTime
        localStorage.setItem('token', newToken)
        localStorage.setItem('tokenExpiry', expiryTime.toString())
        
        return newToken
      } else {
        throw new Error(response.message || '刷新token失败')
      }
    } catch (error) {
      console.error('刷新token失败:', error)
      logout()
      throw error
    }
  }

  /**
   * 注册用户
   * @param {Object} registerData - 注册数据
   * @param {string} registerData.username - 用户名
   * @param {string} registerData.password - 密码
   * @param {string} registerData.email - 邮箱
   * @param {string} registerData.emailCode - 邮箱验证码
   * @param {string} registerData.phone - 手机号
   * @param {string} registerData.smsCode - 手机验证码
   */
  const register = async (registerData) => {
    try {
      const response = await authAPI.register(registerData)
      
      if (response.code === 0) {
        ElMessage.success('注册申请已提交，等待管理员审核')
        return { 
          success: true, 
          data: response.data
        }
      } else {
        ElMessage.error(response.message || '注册失败')
        return { success: false, message: response.message || '注册失败' }
      }
    } catch (error) {
      console.error('注册失败:', error)
      ElMessage.error('注册失败，请重试')
      return { success: false, message: '注册失败' }
    }
  }

  /**
   * 发送邮箱验证码
   * @param {Object} emailData - 邮箱数据
   * @param {string} emailData.email - 邮箱地址
   * @param {string} emailData.type - 验证码类型
   */
  const sendEmailCode = async (emailData) => {
    try {
      const response = await authAPI.sendEmailCode(emailData)
      
      if (response.code === 0) {
        ElMessage.success('邮箱验证码已发送')
        return { 
          success: true, 
          data: response.data
        }
      } else {
        ElMessage.error(response.message || '发送邮箱验证码失败')
        return { success: false, message: response.message || '发送失败' }
      }
    } catch (error) {
      console.error('发送邮箱验证码失败:', error)
      ElMessage.error('发送邮箱验证码失败')
      return { success: false, message: '发送失败' }
    }
  }

  /**
   * 发送手机验证码
   * @param {Object} phoneData - 手机数据
   * @param {string} phoneData.phone - 手机号码
   * @param {string} phoneData.type - 验证码类型
   */
  const sendSmsCode = async (phoneData) => {
    try {
      const response = await authAPI.sendSmsCode(phoneData)
      
      if (response.code === 0) {
        ElMessage.success('手机验证码已发送')
        return { 
          success: true, 
          data: response.data
        }
      } else {
        ElMessage.error(response.message || '发送手机验证码失败')
        return { success: false, message: response.message || '发送失败' }
      }
    } catch (error) {
      console.error('发送手机验证码失败:', error)
      ElMessage.error('发送手机验证码失败')
      return { success: false, message: '发送失败' }
    }
  }

  /**
   * 忘记密码
   * @param {Object} forgotData - 忘记密码数据
   * @param {string} forgotData.email - 邮箱地址
   */
  const forgotPassword = async (forgotData) => {
    try {
      const response = await authAPI.forgotPassword(forgotData)
      
      if (response.code === 0) {
        ElMessage.success('密码重置邮件已发送到您的邮箱')
        return { 
          success: true, 
          data: response.data
        }
      } else {
        ElMessage.error(response.message || '发送重置邮件失败')
        return { success: false, message: response.message || '发送失败' }
      }
    } catch (error) {
      console.error('发送重置邮件失败:', error)
      ElMessage.error('发送重置邮件失败')
      return { success: false, message: '发送失败' }
    }
  }

  /**
   * 重置密码
   * @param {Object} resetData - 重置密码数据
   * @param {string} resetData.token - 重置令牌
   * @param {string} resetData.newPassword - 新密码
   */
  const resetPassword = async (resetData) => {
    try {
      const response = await authAPI.resetPassword(resetData)
      
      if (response.code === 0) {
        ElMessage.success('密码重置成功')
        return { success: true }
      } else {
        ElMessage.error(response.message || '密码重置失败')
        return { success: false, message: response.message || '重置失败' }
      }
    } catch (error) {
      console.error('密码重置失败:', error)
      ElMessage.error('密码重置失败')
      return { success: false, message: '重置失败' }
    }
  }

  /**
   * 强制刷新权限数据
   */
  const refreshPermissions = () => {
    try {
      const stored = localStorage.getItem('permissions')
      if (stored) {
        permissions.value = JSON.parse(stored)
      } else if (isLoggedIn.value) {
        // 如果用户已登录但没有权限数据，设置默认权限
        const defaultPermissions = ['dashboard', 'inspection', 'lines', 'defects', 'remedies', 'statistics']
        permissions.value = defaultPermissions
        localStorage.setItem('permissions', JSON.stringify(defaultPermissions))
      }
    } catch (error) {
      if (isLoggedIn.value) {
        const defaultPermissions = ['dashboard', 'inspection', 'lines', 'defects', 'remedies', 'statistics']
        permissions.value = defaultPermissions
        localStorage.setItem('permissions', JSON.stringify(defaultPermissions))
      }
    }
  }

  /**
   * 更新用户信息
   * @param {Object} newUserInfo - 新的用户信息
   */
  const updateUserInfo = (newUserInfo) => {
    try {
      // 合并用户信息
      userInfo.value = { ...userInfo.value, ...newUserInfo }
      
      // 更新本地存储
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
      
      return { success: true }
    } catch (error) {
      console.error('更新用户信息失败:', error)
      return { success: false, message: '更新失败' }
    }
  }

  return {
    // 状态
    token,
    userInfo,
    permissions,
    isLoggedIn,
    loginTime,
    tokenExpiry,
    
    // 方法
    initAuth,
    clearAuth,
    login,
    logout,
    register,
    sendEmailCode,
    sendSmsCode,
    forgotPassword,
    resetPassword,
    hasPermission,
    getUserInfo,
    refreshToken,
    refreshPermissions,
    updateUserInfo,
    isTokenExpired,
    getRemainingTime
  }
})
